<template>
  <ContentWrap class="chem-record-wrap">
    <div v-if="formData.collectorType" class="chem-header">
      第{{ formData.samplingPeriod }}天样品({{ formData.collectorType }})
    </div>
    <div class="chem-header">
      <div class="chem-title">{{title}}</div>
    </div>
    <!-- 表格 -->
    <el-table :data="form.table" border class="chem-table" stripe table-layout="fixed">
      <el-table-column align="center" label="序号" type="index" />
      <el-table-column align="center" label="检测项目" prop="inspectionItems" width="250px">
        <template #default="{ row }">
          <el-input v-model="row.inspectionItems" placeholder="" @input="onFormChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="测量编号" prop="sampleNo" width="160px">
        <template #default="{ row }">
          <el-input v-model="row.sampleNo" placeholder="" @input="onFormChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="代表/取样场所、岗位、地点" prop="post" width="380px" v-if="props.title!=='样品交接记录表'" >
        <template #default="{ row }">
          <el-input v-model="row.post" placeholder="" @input="onFormChange" :title="row.post"/>
        </template>
      </el-table-column>


      <el-table-column align="center" label="空气收集器" prop="airCollector">
        <template #default="{ row }">
          <el-input v-model="row.airCollector" placeholder="" @input="onFormChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="样品状态" prop="sampleStatus">
        <template #default="{ row }">
          <el-input v-model="row.sampleStatus" placeholder="" @input="onFormChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="采样体积(L)" prop="samplingVolume">
        <template #default="{ row }">
          <el-input v-model="row.samplingVolume" placeholder="" @input="onFormChange" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="样品保存期限和保存条件" prop="preservationConditions" width="260px">
        <template #default="{ row }">
          <el-input v-model="row.preservationConditions" placeholder="" @input="onFormChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="图片上传" prop="image" width="160px" v-if="props.title!=='样品交接记录表'">
        <template #default="{ row, $index }">
          <div v-if="row.inspectionItems && row.inspectionItems.includes('有机')">
            <div v-if="!row.image" class="image-upload">
              <el-upload
                :before-upload="(file) => handleLayoutImageUpload(file, $index)"
                :show-file-list="false"
                accept="image/*"
              >
                <el-button size="small" type="primary">上传图片</el-button>
              </el-upload>
            </div>
            <div v-else class="image-preview">
              <div class="image-item">
                <img :src="row.image" alt="上传的图片" class="preview-img" />
                <el-button
                  class="remove-btn"
                  size="small"
                  type="danger"
                  @click="removeImage($index)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
          <span v-else class="no-upload-text">二氧化硅不用上传图片</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark" width="60px">
        <template #default="{ row }">
          <el-input v-model="row.remark" placeholder="" @input="onFormChange" />
        </template>
      </el-table-column>

    </el-table>
  </ContentWrap>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import type { UploadRawFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { merge } from 'lodash-es'
import { useUpload } from '@/components/UploadFile/src/useUpload'

const { httpRequest } = useUpload()

const route = useRoute()
const router = useRouter()
const form = ref({
  type: '定期检测',
  sampleDate: '',
  projectId: route.query.projectId,
  total: '',
  sampleSender: '',
  sampleTaker: '',
  sampleReceivingTime: '',
  sampleCollector: '',
  sampleCollectorSignature: '',
  sampleCollectionDate: '',
  table: [
    {
      sampleNo: '',
      post: '',
      inspectionItems: '',
      airCollector: '',
      sampleStatus: '',
      samplingVolume: '1',
      preservationConditions: '',
      remark: '',
      image: ''
    }
  ]
})
const loading = ref(false)
const props = defineProps<{
  formData?: any
  title?: any
}>()
// 新增签名弹窗相关

const emit = defineEmits(['update'])

function onFormChange() {
  emit('update', form.value)
}

// 图片上传处理函数
const handleLayoutImageUpload = async (file: File, index: number) => {
  try {
    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('只支持 JPG、PNG、GIF 格式的图片')
      return false
    }

    // 限制文件大小为 2MB
    const maxSize = 1 * 1024 * 1024 // 2MB

    if (file.size > maxSize) {
      ElMessage.error('上传图片大小不能超过 1MB!')
      return false // 阻止上传
    }

    // 创建 UploadRawFile
    const rawFile: UploadRawFile = Object.assign(file, {
      uid: Date.now()
    })

    // 使用 useUpload 上传文件
    const result = await httpRequest({
      file: rawFile,
      filename: file.name,
      data: {},
      headers: {},
      action: '',
      method: 'post',
      onProgress: () => {},
      onError: () => {},
      onSuccess: () => {},
      withCredentials: false
    })

    if (result && typeof result === 'object' && 'data' in result) {
      // 将返回的URL存储为单张图片
      form.value.table[index].image = result.data as string
      ElMessage.success('图片上传成功')
      onFormChange() // 触发更新
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  }
  return false
}

// 删除图片函数
function removeImage(rowIndex: number) {
  form.value.table[rowIndex].image = ''
  onFormChange() // 触发更新
  ElMessage.success('图片删除成功')
}

watch(
  () => props.formData,
  (newData) => {
    console.log('props.formData changed:', JSON.stringify(newData))
    form.value = merge({}, form.value, newData)
  },
  { immediate: true, deep: true }
)
</script>

<style lang="scss" scoped>
.chem-title {
  font-size: 26px;
  font-weight: 600;
  color: #222;
  flex-grow: 1;
  text-align: center;
}

.chem-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 0 24px 0;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e6eb;
}

.header-container-consumable {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e6eb;
}

.centered-title-equipment {
  text-align: center; // Center the text
  flex-grow: 1; // Allow title to take available space to help centering
  margin: 0; // Remove default margin
  font-size: 24px; // Match Consumable title size
  font-weight: bold;
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;

  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  // 设置表格行高
  :deep(.el-table__body td) {
    border-radius: 0 !important;

    font-size: 14px;
    padding: 0 !important;
    // 列和单元格的边距
    .cell {
      padding: 0px 0px;
    }
  }

  // 去掉输入框边框
  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}

.input-with-unit {
  position: relative;
}

:deep(.el-input__inner) {
  text-align: center;
}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}

// 图片上传相关样式
.image-upload {
  margin-bottom: 8px;
}

.image-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.preview-img {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
}

.remove-btn {
  font-size: 12px;
  padding: 2px 8px;
  height: auto;
}

.no-upload-text {
  color: #909399;
  font-size: 12px;
  text-align: center;
  display: block;
  padding: 8px;
}
</style>
